package cn.tedu.charging.user.service;

import cn.tedu.charging.common.constant.AppInfoConst;
import cn.tedu.charging.common.enums.VehicleUserBindEnum;
import cn.tedu.charging.common.pojo.param.ChargeParam;
import cn.tedu.charging.common.pojo.param.VehicleBindParam;
import cn.tedu.charging.common.pojo.po.ChargingUserInfoPO;
import cn.tedu.charging.common.pojo.po.ChargingUserVehicleBindPO;
import cn.tedu.charging.common.pojo.po.ChargingVehiclePO;
import cn.tedu.charging.common.pojo.vo.BalanceVO;
import cn.tedu.charging.common.pojo.vo.VehicleVO;
import cn.tedu.charging.common.protocol.JsonResult;
import cn.tedu.charging.user.dao.repository.UserRepository;
import cn.tedu.charging.user.dao.repository.UserVehicleRepository;
import cn.tedu.charging.user.dao.repository.VehicleRepository;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

@Service
@Slf4j
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private VehicleRepository vehicleRepository;
    @Autowired
    private UserVehicleRepository userVehicleRepository;

    RestTemplate restTemplate = new RestTemplate();

    String url= "https://api.weixin.qq.com/sns/jscode2session?appId={1}&secret={2}&js_code={3}&grant_type=authorization_code";

    public Integer wxLogin(String code, String nickName) {
        String result = restTemplate.getForObject(url, String.class, AppInfoConst.APP_ID, AppInfoConst.APP_SECRET, code);
        log.info("微信登录返回结果：{}",result);
        String openId = null;
        if (result!=null && result.length()>0){
            JSONObject jsonObject = JSONObject.parseObject(result);
            openId  = (String) jsonObject.get("openid");
        }
        if (openId==null ){
            throw new RuntimeException("拿不到合法的openId");
        }
        log.info("openId:{}",openId);
        //查询是否有该用户
       ChargingUserInfoPO userInfoPO = userRepository.getUserByOpenId(openId);
        if (userInfoPO==null){
            userInfoPO = new ChargingUserInfoPO();
            userInfoPO.setWxOpenId(openId);
            userInfoPO.setNickName(nickName);
            userInfoPO.setCreateTime(new Date());
            userInfoPO.setUpdateTime(new Date());
            userRepository.insertUser(userInfoPO);
            return userInfoPO.getId();
        }
        return userInfoPO.getId();
    }

    public VehicleVO bindeVehicle(Integer userId) {
        Integer vehicleId=userVehicleRepository.getUserBindedVehicleId(userId,VehicleUserBindEnum.BINDED.getState());
        VehicleVO vo = new VehicleVO();
        if(vehicleId!=null){
         ChargingVehiclePO po=vehicleRepository.getVehicleDetailById(vehicleId);
         if (po!=null){
             vo = new VehicleVO();
             BeanUtils.copyProperties(po,vo);
             return vo;
         }
        }
        return vo;
    }

    public Integer bindVehicle(VehicleBindParam param) {
        Integer vehicleId = userVehicleRepository.getUserBindedVehicleId(param.getUserId(), VehicleUserBindEnum.BINDED.getState());
        if (vehicleId!=null){
          throw new RuntimeException("该用户已绑定过车");
        }
        //根据车牌号查询车辆存不存在
       ChargingVehiclePO po =  vehicleRepository.getVehicleByLicense(param.getLicense());
        if (po==null){
           po= new ChargingVehiclePO();
           BeanUtils.copyProperties(param,po);
           po.setCreateTime(new Date());
           po.setUpdateTime(new Date());
           vehicleRepository.insertVehicle(po);
        }
        ChargingUserVehicleBindPO bindPO = new ChargingUserVehicleBindPO();
        bindPO.setUserId(param.getUserId());
        bindPO.setVehicleId(po.getId());
        bindPO.setState(VehicleUserBindEnum.BINDED.getState());
        bindPO.setCreateTime(new Date());
        userVehicleRepository.insertUserVehicleBind(bindPO);
        return po.getId();
    }

    public Integer unbindVehicle(Integer userId) {
        //根据用户id查询绑定关系
        Integer vehicleId = userVehicleRepository.getUserBindedVehicleId(userId, VehicleUserBindEnum.BINDED.getState());
        if (vehicleId==null){
            throw new RuntimeException("该用户没有绑定车辆");
        }
        vehicleRepository.deleteById(vehicleId);
        userVehicleRepository.updateUserVehicleByUserIdAndState(userId);
        return vehicleId;
    }

    public BalanceVO getBalance(Integer userId) {
        BalanceVO balanceVO = new BalanceVO();
        balanceVO.setBalance(userRepository.getUserById(userId).getBalance());
        log.info("用户余额：{}",balanceVO.getBalance());
        return balanceVO;
    }

    public void charge(ChargeParam param) {
        userRepository.updateUserBalance(param.getUserId(),param.getAmount());
    }
}
